package com.tanhua.backstage.controller;

import cn.hutool.core.util.StrUtil;
import com.tanhua.backstage.service.CheckService;
import com.tanhua.backstage.service.UserService;
import com.tanhua.common.pojo.BsUser;
import com.tanhua.common.utils.BsUserThreadLocal;
import com.tanhua.common.utils.NoAuthorization;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("system/users")
public class LoginController {
    @Autowired
    private CheckService checkService;
    @Autowired
    private UserService userService;
    /**
     * 控制层实现功能:获取验证码
     *
     * @param uuid
     * @param request
     * @param response
     * @throws IOException
     */
    @NoAuthorization
    @GetMapping("verification")
    public void getCode(@RequestParam("uuid") String uuid, HttpServletRequest request, HttpServletResponse response) throws IOException {
        BufferedImage image = checkService.getImage(uuid);
        //返回验证码到登录页面
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    /**
     * 获取用户基本信息
     * @return
     */
    @PostMapping("profile")
    public ResponseEntity<Map<String,String>> getBsUserInfo() {
        try {
            //token校验通过 通过本地线程获取用户基本信息
            BsUser bsUser = BsUserThreadLocal.get();
            Map<String,String> map = new HashMap<>();
            map.put("uid", StrUtil.toString(bsUser.getId()));
            map.put("username",bsUser.getUsername());
            map.put("avatar",bsUser.getAvatar());
            return ResponseEntity.ok(map);
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 控制层实现功能:用户退出登录
     * @return
     */
    @PostMapping("logout")
    @NoAuthorization
    public void logoutBsUser(@RequestHeader("Authorization") String token,HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
        String realToken = token.split(" ")[1];
        //删除redis中的token
        userService.logoutBsUser(realToken);
    }
}
